package com.fang.transfer.file.listener;

import com.fang.transfer.file.ThreadContext;
import com.fang.transfer.file.common.NettyHandle;
import com.fang.transfer.file.common.RequestListener;
import com.fang.transfer.file.common.code.ClientSendCode;
import com.fang.transfer.file.common.code.ServiceSendCode;
import com.fang.transfer.file.common.model.TransferFileRequest;
import com.fang.transfer.file.common.model.User;
import com.fang.transfer.file.service.FileSendRequestService;
import com.fang.transfer.file.service.UserService;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 收到用户打洞成功请求
 */
@Service
public class UpdHoleSuccessListener extends RequestListener<TransferFileRequest> {

    @Autowired
    private NettyHandle nettyHandle;
    @Autowired
    private FileSendRequestService fileSendRequestService;

    @Override
    public void handle(TransferFileRequest param) {
        ChannelHandlerContext channelHandlerContext = ThreadContext.getChannelHandlerContext();
        String id = channelHandlerContext.channel().id().toString();
        TransferFileRequest request = fileSendRequestService.getById(param.getId());
        String sendUserId = request.getSendUser().getId();
        int status = id.equals(sendUserId) ? 31 : 32;
        if (request.getStatus() == 4) {
            return;
        }
        if (request.getStatus() == status) {
            return;
        }

        if (request.getStatus() == 3) {
            request.setStatus(status);
            return;
        }
        request.setStatus(4);
        User receiveUser = request.getReceiveUser();
        nettyHandle.send(receiveUser.getId(), ServiceSendCode.FILE_CHECK, request);
    }

    @Override
    public String getCode() {
        return ClientSendCode.UPD_HOLE_SUCCESS;
    }

}
